﻿Imports System.Windows
Imports CommunityToolkit.Mvvm.ComponentModel
Imports CommunityToolkit.Mvvm.Input

Public Class MyBlogPageViewModel : Inherits ObservableObject

    Private _blogList As List(Of Blog)
    Public Property BlogList As List(Of Blog)
        Get
            Return _blogList
        End Get
        Set(value As List(Of Blog))
            SetProperty(_blogList, value)
            Call UpdateICList()
        End Set
    End Property

    'TODO: 将 MyBlogPage.xaml.vb 里 ItemControl 对用户控件管理的逻辑移到此处
    Private _ic_list As List(Of MyBlogItem)
    Public Property IC_List As List(Of MyBlogItem)
        Get
            Return _ic_list
        End Get
        Set(value As List(Of MyBlogItem))
            SetProperty(_ic_list, value)
        End Set
    End Property

    Private ReadOnly _client As HttpClientBase

    Public Property CreateNewBlogCommand As New RelayCommand(AddressOf CreateNewBlogClicked)

    Public Sub New()
        _client = New HttpClientBase()
        IC_List = New List(Of MyBlogItem)
        Call GetMyBlogListAsync()
    End Sub

    Private Async Function GetMyBlogListAsync() As Task
        Try
            Dim response = Await _client.GetAsync(Of List(Of Blog))("vdm/api/blog/getBlog/uid/" + Application.Current.Resources("UserId").ToString())
            If response.Code = 200 Then
                BlogList = response.Data
                Console.WriteLine("GetMyBlogListAsync: " + BlogList.ToString())
            Else
                MessageBox.Show("获取漂流瓶信息失败：" + response.Message)
            End If
        Catch ex As Exception
            MessageBox.Show("系统错误：" + ex.Message)
            NavigationService.Navigate(NavigationData.LOGIN_PAGE_URI)
        End Try
    End Function

    Private Sub CreateNewBlogClicked()
        NavigationService.Navigate(Of NewBlogPage)()
    End Sub

    Private Async Function UpdateICList() As Task
        Dim blogItems As New List(Of MyBlogItem)
        If BlogList Is Nothing OrElse BlogList.Count = 0 Then
            Return
        End If
        '根据 blogList 渲染 UserControl(MyBlogItem.xaml)
        Console.WriteLine("UpdateICList COUNT: " + BlogList.Count.ToString())
        For Each blog In BlogList
            Dim myBlogItem As New MyBlogItem()
            myBlogItem.DataContext = blog
            myBlogItem.TB_Date.Text = blog.PostDate.ToString("yyyy-MM-dd")
            Await myBlogItem.LoadSongTitleAsync()
            blogItems.Add(myBlogItem)
        Next
        IC_List = blogItems
    End Function

End Class
